package com.systemsetup.systemsetup.web.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.systemsetup.systemsetup.common.base.BaseService;
import com.systemsetup.systemsetup.common.utils.Base64Util;
import com.systemsetup.systemsetup.common.utils.MD5Util;
import com.systemsetup.systemsetup.common.utils.PasswordUtil;
import com.systemsetup.systemsetup.model.*;
import com.systemsetup.systemsetup.support.model.RespEntity;
import com.systemsetup.systemsetup.support.utils.requestutil.HttpRequestUtil;
import com.systemsetup.systemsetup.web.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@Slf4j
public class SystemsetupService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(SystemsetupService.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userroleMapper;
    @Resource
    private UserPermissionMapper userpermissionMapper;
    @Resource
    private RolepermissionMapper rolepermissionMapper;
    @Resource
    private PermissionsMapper permissionsMapper;
    @Resource
    AppversionMapper appversionMapper;
    @Resource
    private UserService userService;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private WeChatMapper weChatMapper;
    @Resource
    private TitlePictureMapper titlePictureMapper;
    @Resource
    private TextTitleMapper textTitleMapper;
    @Resource
    private HomePageLayoutInfoMapper homePageLayoutInfoMapper;
    @Resource
    private HomePageLayoutMapper homePageLayoutMapper;
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private FrameMonitoringMapper frameMonitoringMapper;
    @Resource
    private LargeScreenSettingsMapper largeScreenSettingsMapper;
    @Resource
    private AerialViewCoordinateMapper aerialViewCoordinateMapper;
    @Resource
    private ToppedApplicationInfoMapper toppedApplicationInfoMapper;
    @Resource
    private RenewInfoMapper renewInfoMapper;


    public RespEntity userDetail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = jsonParam.getStr("id");//用户id
        List<User> userList = userMapper.selectList(new QueryWrapper<User>().eq("id", userId));
        User user = userList.get(0);
        Integer type = user.getType();//账户类型：1 机构账户  2 单位账户

        //机构用户
        if (type == 1) {//机构用户
            Organization organization = organizationMapper.selectById(user.getHomeId());
            user.put("homeName", organization.getName());
        } else if (type == 2) {//单位用户
            String departmentId = user.getDepartmentId();
            if (departmentId != null && StrUtil.isNotBlank(departmentId)) {
                if (departmentId.equals("0")) {
                    user.put("departmentName", "总部");
                } else {
                    String departName = departmentMapper.selectById(departmentId).getName();
                    user.put("departmentName", departName);
                }
            }
        }
        //查询用户权限id
        List<Userpermission> userpermissionList = userpermissionMapper.selectList(new QueryWrapper<Userpermission>().eq("user_id", user.getId()));
        //总权限列表
        List<Permissions> permissionsList = permissionsMapper.getUserPermissionsList(user.getId());
        //第一级权限
        List<Permissions> onePermissionsList = new ArrayList<>();
        //第二级权限
        List<Permissions> twoPermissionsList = new ArrayList<>();
        //第三级权限
        List<Permissions> threePermissionsList = new ArrayList<>();
        //第四级权限
        List<Permissions> fourPermissionsList = new ArrayList<>();
        for (Permissions list : permissionsList) {
            if (list.getLevel() == 1) {
                onePermissionsList.add(list);
            }
            if (list.getLevel() == 2) {
                twoPermissionsList.add(list);
            }
            if (list.getLevel() == 3) {
                threePermissionsList.add(list);
            }
            if (list.getLevel() == 4) {
                fourPermissionsList.add(list);
            }
        }
        for (Permissions one : onePermissionsList) {
            List<Permissions> twoNewPermissionsList = new ArrayList<>();
            for (Permissions two : twoPermissionsList) {
                if (one.getId().equals(two.getPid())) {
                    List<Permissions> threeNewPermissionsList = new ArrayList<>();
                    for (Permissions three : threePermissionsList) {
                        if (two.getId().equals(three.getPid())) {
                            List<Permissions> fourNewPermissionsList = new ArrayList<>();
                            for (Permissions four : fourPermissionsList) {
                                if (three.getId().equals(four.getPid())) {
                                    four = getUserPermissions(four, userpermissionList);
                                    fourNewPermissionsList.add(four);
                                }
                            }
                            if (fourNewPermissionsList.size() != 0) {
                                three.put("childList", fourNewPermissionsList);
                            }
                            three = getUserPermissions(three, userpermissionList);
                            threeNewPermissionsList.add(three);
                        }
                    }
                    if (threeNewPermissionsList.size() != 0) {
                        two.put("childList", threeNewPermissionsList);
                    }
                    two = getUserPermissions(two, userpermissionList);
                    twoNewPermissionsList.add(two);
                }
            }
            if (twoNewPermissionsList.size() != 0) {
                one.put("childList", twoNewPermissionsList);
            }
            one = getUserPermissions(one, userpermissionList);
        }
        user.set("permissionsList", onePermissionsList);
        return RespEntity.success(user);
    }

    //权限校验
    public Permissions getUserPermissions(Permissions permission, List<Userpermission> userpermissionList) {
        boolean flag = false;
        for (Userpermission userpermission : userpermissionList) {
            if (permission.getId().equals(userpermission.getPermissionId())) {
                flag = true;
            }
        }
        permission.put("flag", flag);
        return permission;
    }

    /**
     * 单位删除的时候调用
     * 查看本单位是否还有启用的账号
     *
     * @param jsonParam
     * @return
     */
    public int userCount(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询单位是否存在启用账号
        int userNum = userMapper.selectCount(new QueryWrapper<User>().eq("home_id", jsonParam.getStr("businessId")).eq("is_use", 1).eq("type", 2));

        return userNum;
    }

    /**
     * 用户修改
     *
     * @param
     * @return
     */
    public RespEntity userUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String userId = token.getString("user_id");
        String id = jsonParam.getStr("id");
        if (StrUtil.isBlank(id)) {
            return RespEntity.fail("id不能为空");
        }
        User user = userMapper.selectById(id);
        if (user == null) {
            return RespEntity.fail("传入的id错误");
        }
        int count = userMapper.getSameUserNameListSize(jsonParam);
        if (count > 0) {
            return RespEntity.fail("用户名已存在");
        }
        String accountpasswordOld = user.getAccountpassword();
        String accountpasswordNew = jsonParam.getStr("accountpassword");
        //用户传过来的参数
        String name = jsonParam.getStr("name");
        String accountname = jsonParam.getStr("accountname");
        if (accountpasswordOld.equals(accountpasswordNew)) {
            user.setAccountpassword(accountpasswordOld);
        } else {
            String accountpassword = PasswordUtil.createHash(jsonParam.getStr("accountpassword"));
            user.setAccountpassword(accountpassword);
        }
        String phone = jsonParam.getStr("phone");
        String email = jsonParam.getStr("email");
        String shomeId = jsonParam.getStr("homeId");
        String roleId = jsonParam.getStr("roleId");
        user.setAccountname(accountname);
        user.setName(name);
        user.setPhone(phone);
        user.setEmail(email);
        user.setRoleId(roleId);
        user.setId(id);
        //修改user数据库
        userMapper.updateById(user);
        List<Rolepermission> rolepermissionList = rolepermissionMapper.selectList(new QueryWrapper<Rolepermission>().eq("role_id", roleId));
        List<Userpermission> list = new ArrayList<>();
        for (Rolepermission rolepermission : rolepermissionList) {
            //权限设置
            Userpermission userpermission = new Userpermission();
            userpermission.setUserId(user.getId());
            userpermission.setPermissionId(rolepermission.getPermissionId());
            userpermission.setCreatetime(user.getCreatetime());
            list.add(userpermission);
        }
        //删除原来数据再添加
        userpermissionMapper.delete(new QueryWrapper<Userpermission>().eq("user_id", user.getId()));
        userpermissionMapper.insertZB(list);
//        if (jsonParam.containsKey("permissionIds")){
//            if (!jsonParam.getStr("permissionIds").equals("")){
//                //权限id
//                String [] ids = jsonParam.getStr("permissionIds").split(",");
//                List<Userpermission> list = new ArrayList<>();
//                if (ids!=null && ids.length!=0){
//                    for (String permissionsId : ids){
//                        //权限设置
//                        Userpermission userpermission = new Userpermission();
//                        userpermission.setUserId(user.getId());
//                        userpermission.setPermissionId(permissionsId);
//                        userpermission.setCreatetime(user.getCreatetime());
//                        list.add(userpermission);
//                    }
//                    //删除原来数据再添加
//                    userpermissionMapper.delete(new QueryWrapper<Userpermission>().eq("user_id",user.getId()));
//                    userpermissionMapper.insertZB(list);
//                }
//            }
//        }
        return RespEntity.success();
    }

    /**
     * 用户新增
     *
     * @param
     * @return
     */
    public RespEntity userAdd(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String userId = token.getString("user_id");
        int count = userMapper.getSameUserNameListSize(jsonParam);
        if (count > 0) {
            return RespEntity.fail("用户名已存在");
        }
        //用户传过来的参数
        String name = jsonParam.getStr("name");
        String accountname = jsonParam.getStr("accountname");
        String accountpassword = PasswordUtil.createHash(jsonParam.getStr("accountpassword"));
        String phone = jsonParam.getStr("phone");
        String email = jsonParam.getStr("email");
        String shomeId = jsonParam.getStr("homeId");
        String roleId = jsonParam.getStr("roleId");
        String departmentId = jsonParam.getStr("departmentId");
        if (jsonParam.getInt("type") == 2) {//2 单位账户
            if (departmentId == null || StrUtil.isBlank(departmentId)) {
                departmentId = "0";
            }
        }
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setAccountname(accountname);
        user.setAccountpassword(accountpassword);
        user.setName(name);
        user.setIsUse(1);
        user.setPhone(phone);
        user.setEmail(email);
        user.setRoleId(roleId);
        user.setDepartmentId(departmentId);
        if (StrUtil.isBlank(shomeId)) {
            user.setHomeId(homeId);
        } else {
            user.setHomeId(shomeId);
        }
        user.setCreatetime(new Date());
        user.setType(jsonParam.getInt("type"));
        //修改user数据库
        userMapper.insert(user);
        List<Rolepermission> rolepermissionList = rolepermissionMapper.selectList(new QueryWrapper<Rolepermission>().eq("role_id", roleId));
        List<Userpermission> list = new ArrayList<>();
        for (Rolepermission rolepermission : rolepermissionList) {
            //权限设置
            Userpermission userpermission = new Userpermission();
            userpermission.setUserId(user.getId());
            userpermission.setPermissionId(rolepermission.getPermissionId());
            userpermission.setCreatetime(user.getCreatetime());
            list.add(userpermission);
        }
        userpermissionMapper.insertZB(list);
//        if (jsonParam.containsKey("permissionIds")){
//            if (!jsonParam.getStr("permissionIds").equals("")){
//                //权限id
//                String [] ids = jsonParam.getStr("permissionIds").split(",");
//                List<Userpermission> list = new ArrayList<>();
//                if (ids!=null && ids.length!=0){
//                    for (String permissionsId : ids){
//                        //权限设置
//                        Userpermission userpermission = new Userpermission();
//                        userpermission.setUserId(user.getId());
//                        userpermission.setPermissionId(permissionsId);
//                        userpermission.setCreatetime(user.getCreatetime());
//                        list.add(userpermission);
//                    }
//                    userpermissionMapper.insertZB(list);
//                }
//            }
//        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 创建舆情平台子帐号并绑定
     * @Date Created in 14:20 2023/4/19
     * @Param [jsonParam]
     */

    public RespEntity accountContactCreateSub(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String userId = token.getString("user_id");

        String id = jsonParam.getStr("id");
        if (StrUtil.isBlank(id)) {
            return RespEntity.fail("id不能为空");
        }
        User user = userMapper.selectById(id);
        //参数
        Dict dict = new Dict();
        dict.set("name", user.getName());
        dict.set("userId", user.getId());
        dict.set("adminId", "szkjsd01");
        dict.set("platform", "EXAMPLE");
        try {
            JSONObject jsonObject = getRest(dict, "wuyouyuqing", "accountContactCreateSub", "yuqing");
            if (jsonObject.getBool("succ")) {
                return RespEntity.success();
            } else {
                return RespEntity.fail(jsonObject.getStr("msg"));
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 免鉴权平台 用户验证并登录
     * @Date Created in 14:20 2023/4/19
     * @Param [jsonParam]
     */

    public RespEntity accountContactCheck(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String userId = token.getString("user_id");

        //舆情平台秘钥
        String secretKey = "U0QyM13ca41NERlM8c";
        String md5SecretKey = MD5Util.encode2hex(secretKey);
        //平台标识
        String identification = "EXAMPLE";
        //账号base64加密
        String userIdBase64 = "";
        if (userId.equals("930d2e85-2d5d-4be9-b831-ef7290a2cf12")) {
            userIdBase64 = Base64Util.strToBase64(identification + "-szkjsd01");
        } else {
            userIdBase64 = Base64Util.strToBase64(identification + "-" + userId);
        }
        // 加密凭证
        String certificate = Base64Util.strToBase64(md5SecretKey.substring(0, 16) + userIdBase64);
        //参数
        Dict dict = new Dict();
        dict.set("certificate", certificate);
        dict.set("platform", identification);
        try {
            JSONObject jsonObject = getRest(dict, "wuyouyuqing", "accountContactCheck", "yuqing");
            if (jsonObject.getBool("succ")) {
                return RespEntity.success(jsonObject.getStr("msg"));
            } else {
                return RespEntity.fail("请联系我们开通服务!");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return RespEntity.success();
    }

    public static void main(String[] args) {
        System.out.println(PasswordUtil.createHash("Firelink@123"));
    }

    /**
     * 权限列表
     *
     * @param jsonParam
     * @return
     */

    public RespEntity permissionsTreeList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String userId = token.getString("user_id");

        //总权限列表
        List<Permissions> permissionsList = permissionsMapper.getUserPermissionsList(userId);
        Map<String, Object> map = new HashMap<>();
        //第一级权限
        List<Permissions> onePermissionsList = new ArrayList<>();
        //第二级权限
        List<Permissions> twoPermissionsList = new ArrayList<>();
        //第三级权限
        List<Permissions> threePermissionsList = new ArrayList<>();
        //第四级权限
        List<Permissions> fourPermissionsList = new ArrayList<>();
        for (Permissions list : permissionsList) {
            if (list.getLevel() == 1) {
                onePermissionsList.add(list);
            }
            if (list.getLevel() == 2) {
                twoPermissionsList.add(list);
            }
            if (list.getLevel() == 3) {
                threePermissionsList.add(list);
            }
            if (list.getLevel() == 4) {
                fourPermissionsList.add(list);
            }
        }
        for (Permissions one : onePermissionsList) {
            List<Permissions> twoNewPermissionsList = new ArrayList<>();
            for (Permissions two : twoPermissionsList) {
                if (one.getId().equals(two.getPid())) {
                    List<Permissions> threeNewPermissionsList = new ArrayList<>();
                    for (Permissions three : threePermissionsList) {
                        if (two.getId().equals(three.getPid())) {
                            List<Permissions> fourNewPermissionsList = new ArrayList<>();
                            for (Permissions four : fourPermissionsList) {
                                if (three.getId().equals(four.getPid())) {
                                    fourNewPermissionsList.add(four);
                                }
                            }
                            if (fourNewPermissionsList.size() != 0) {
                                three.put("childList", fourNewPermissionsList);
                            }
                            threeNewPermissionsList.add(three);
                        }
                    }
                    if (threeNewPermissionsList.size() != 0) {
                        two.put("childList", threeNewPermissionsList);
                    }
                    twoNewPermissionsList.add(two);
                }
            }
            if (twoNewPermissionsList.size() != 0) {
                one.put("childList", twoNewPermissionsList);
            }
        }
        map.put("name", "权限管理");
        map.put("level", "0");
        map.put("pid", "-1");
        map.put("id", "0");
        map.put("childList", onePermissionsList);
        return RespEntity.success(map);
    }

    /**
     * 用户列表
     *
     * @param jsonParam
     * @return
     */

    public RespEntity userListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        if (StrUtil.isBlank(jsonParam.getStr("orgId"))) {
            jsonParam.remove("orgId");
        }
        Page<DeviceBusiness> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        IPage<User> pageList = null;
        if (userType.equals("1")) {//为机构用户
            //机构查询企业账户列表
            if (StrUtil.isNotBlank(jsonParam.getStr("queryhomeId"))) {
                jsonParam.put("businessId", jsonParam.getStr("queryhomeId"));
                pageList = userMapper.userListForBUPage(page, jsonParam);
            } else {
                if (StrUtil.isNotBlank(jsonParam.getStr("orgId"))) {//点左边的树
                    jsonParam.put("orgId", jsonParam.getStr("orgId"));
                } else {//rest请求系统设置模块的本机构和子机构列表接口
                    jsonParam.put("orgId", homeId);
                }
//                JSON jsons = makeDataForJSONForToken(jsonParam,"systemsetup","config","getOrgAllList","systemsetup");
//                if(jsons instanceof com.alibaba.fastjson.JSONObject){
//                    com.alibaba.fastjson.JSONObject weekAlarmObjectN = (com.alibaba.fastjson.JSONObject)jsons;
//                    if(StrUtil.isNotBlank(weekAlarmObjectN.getString("methodCodeFlag"))){
//                        return RespEntity.expire();
//                    }
//                    return RespEntity.fail(((com.alibaba.fastjson.JSONObject) jsons).getString("msg"));
//                }else{
//                    com.alibaba.fastjson.JSONArray orgIdList = (com.alibaba.fastjson.JSONArray)jsons;
//                    if(orgIdList!=null && !orgIdList.isEmpty()){
//                        jsonParam.put("orgIdList",orgIdList);
//                        jsonParam.put("orgIdListFlag","1");
//                    }
//                }
                pageList = userMapper.userListPage(page, jsonParam);
            }
        } else if (userType.equals("2")) {//为单位用户
            jsonParam.put("businessId", homeId);
            pageList = userMapper.userListForBUPage(page, jsonParam);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * 获取最新版本
     *
     * @param jsonParam
     * @return
     */

    public RespEntity getNewestVersionUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        if (StrUtil.isBlank(jsonParam.getStr("version"))) {
            return RespEntity.fail("没有传入当前版本号");
        }
        List<Appversion> list = appversionMapper.selectList(new QueryWrapper<Appversion>().orderByDesc("sortid"));
        if (!list.isEmpty()) {
            Appversion appversion = list.get(0);
            if (appversion.getVersionCode().equals(jsonParam.getStr("version"))) {
                appversion.put("code", 0);
            } else {
                appversion.put("code", 1);
            }
            return RespEntity.success(appversion);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 世成电器app版本
     * @Date Created in 9:42 2022/8/16
     * @Param [jsonParam]
     */

    public JSONObject getAppVersionScList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        JSONObject jsonObject = new JSONObject();
        if (StrUtil.isBlank(jsonParam.getStr("version"))) {
            jsonObject.put("msg", "没有传入当前版本号");
            jsonObject.put("code", 1);
            return jsonObject;
        }
        List<Appversion> list = appversionMapper.getAppVersionScList();
        if (!list.isEmpty()) {
            Appversion appversion = list.get(0);
            jsonObject.put("msg", "success");
            if (appversion.getVersionCode().equals(jsonParam.getStr("version"))) {
                jsonObject.put("code", 0);
            } else {
                jsonObject.put("code", 1);
            }
            jsonObject.put("data", appversion);
            return jsonObject;
        }
        jsonObject.put("code", 1);
        return jsonObject;
    }

    /**
     * 设置文字标题
     *
     * @param jsonParam
     * @return
     */
    public RespEntity setTextTitle(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        JSONArray lists = jsonParam.getJSONArray("list");
        for (Object list : lists) {
            JSONObject json = (JSONObject) list;
            String homeId = json.getStr("homeId");
            String deviceClassify = json.getStr("deviceClassify");
            String titleText = json.getStr("titleText");
            TextTitle textTitle = new TextTitle();
            textTitle.setId(UUID.randomUUID().toString());
            textTitle.setHomeId(homeId);
            textTitle.setDeviceClassify(deviceClassify);
            textTitle.setTitleText(titleText);
            this.textTitleMapper.delete(new QueryWrapper<TextTitle>().eq("device_classify", deviceClassify).eq("home_id", homeId));
            int insert = this.textTitleMapper.insert(textTitle);
            if (insert < 0) {
                return RespEntity.fail();
            }
        }
        return RespEntity.success();
    }

    /**
     * 获取文字标题
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getTextTitle(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = jsonParam.getStr("homeId");
        //String deviceClassify = jsonParam.getStr("deviceClassify");
        //String titleText = jsonParam.getStr("titleText");
        if (homeId == null || homeId.equals("")) {
            return RespEntity.fail("未获取到该机构的信息！请稍后再试。");
        }
        List<TextTitle> list = this.textTitleMapper.selectList(new QueryWrapper<TextTitle>().eq("home_id", homeId));
        return RespEntity.success(list);
    }


    /**
     * @Author YangYu
     * @Description 获取首页布局信息
     * @Date Created in 9:41 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity getHomePageLayoutList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        if (jsonParam.containsKey("recovery")) {
            List<HomePageLayout> homePageLayoutList = homePageLayoutMapper.selectList(new QueryWrapper<>());
            return RespEntity.success(homePageLayoutList);
        }
        List<HomePageLayoutInfo> layoutInfoList = homePageLayoutInfoMapper.selectList(new QueryWrapper<HomePageLayoutInfo>().eq("home_id", jsonParam.getStr("homeId")));
        if (layoutInfoList.isEmpty()) {
            List<HomePageLayout> homePageLayoutList = homePageLayoutMapper.selectList(new QueryWrapper<>());
            return RespEntity.success(homePageLayoutList);
        }
        return RespEntity.success(layoutInfoList);
    }

    /**
     * @Author YangYu
     * @Description 设置首页布局信息
     * @Date Created in 9:41 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity setHomePageLayoutList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");

        List<HomePageLayoutInfo> layoutInfoList = new ArrayList<>();
        if (userType.equals("1")) {
            int count = homePageLayoutInfoMapper.selectCount(new QueryWrapper<HomePageLayoutInfo>().eq("home_id", homeId));
            if (count > 0) {
                homePageLayoutInfoMapper.delete(new QueryWrapper<HomePageLayoutInfo>().eq("home_id", homeId));
            }
            JSONArray jsonArray = jsonParam.getJSONArray("item");
            //遍历jsonArray
            for (Object object : jsonArray) {
                JSONObject json = (JSONObject) object;
                HomePageLayoutInfo homePageLayoutInfo = new HomePageLayoutInfo();
                homePageLayoutInfo.setId(UUID.randomUUID().toString());
                homePageLayoutInfo.setSubtitleName(json.getStr("subtitleName"));
                homePageLayoutInfo.setHeadlineName(json.getStr("headlineName"));
                homePageLayoutInfo.setHomeId(homeId);
                homePageLayoutInfo.setLogo(json.getStr("logo"));
                homePageLayoutInfo.setPermissionsId(json.getStr("permissionsId"));
                layoutInfoList.add(homePageLayoutInfo);
            }
            homePageLayoutInfoMapper.insertZB(layoutInfoList);
        } else {
            return RespEntity.fail("不是机构账户无权设置!");
        }
        return RespEntity.success();
    }

    /**
     * 单位获取账号列表
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getUserList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        List<User> userList = userMapper.getUserList(homeId);
        for (Object obj : userList) {
            Map<String, Object> user = (Map<String, Object>) obj;
            mapList.add(user);
        }
        return RespEntity.success(mapList);
    }

    public RespEntity orgAllList(JSONObject jsonParam, HttpServletRequest httpServletRequest) {
        /*1 首先说明这个机构数的下级是无限极，所以需要使用递归
        2 如传参orgId为空：
        首先获取登陆者的信息，获取他所属的机构id；（形式可以是token解析出信息，也可以调用登录模块获取，
        这个需要看登录模块的设计），最好在一个工具类或者BaseService里边写一个获取登录者信息的方法，
        以便该模块接口中随时获取；
        传参不为空：则用传参的机构id
        3 有了机构id，就可以在机构表中递归了；
        4 最终所有数据组成一个对象列表*/
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");

        String orgId = jsonParam.getStr("orgId");
        if (StrUtil.isBlank(orgId)) {
            jsonParam.put("orgId", homeId);
        }
        List<Organization> organizations = organizationMapper.getOrganizations(jsonParam);
        return RespEntity.success(organizations);
    }

    /**
     * @Author YangYu
     * @Description 机构和子机构列表(递归查询)
     * @Date Created in 15:10 2023/2/2
     * @Param [jsonParam, httpServletRequest]
     */
    public static final List<Organization> list = new ArrayList<>();

    public RespEntity getOrgAllList(JSONObject jsonParam, HttpServletRequest httpServletRequest) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");

        String orgId = jsonParam.getStr("orgId");
        list.clear();
        if (StrUtil.isBlank(orgId)) {
            jsonParam.put("orgId", homeId);
        }
        Organization organization = organizationMapper.selectById(jsonParam.getStr("orgId"));
        List<Organization> orgs = getOrganizations(jsonParam.getStr("orgId"));
        orgs.add(organization);
        return RespEntity.success(orgs);
    }

    //递归调用
    public List<Organization> getOrganizations(String id) {
        List<Organization> oneList = organizationMapper.selectList(new QueryWrapper<Organization>().eq("pid", id));
        for (Organization one : oneList) {
            List<Organization> twoList = getOrganizations(one.getId());
            list.add(one);
        }
        return list;
    }

    /**
     * 账号不分页列表
     *
     * @param jsonParam
     * @param httpServletRequest
     * @return
     */
    public RespEntity userList(JSONObject jsonParam, HttpServletRequest httpServletRequest) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        List<User> userList = new ArrayList<>();
        if (StrUtil.isBlank(jsonParam.getStr("homeId"))) {
            jsonParam.put("homeId", homeId);
            //1 机构账户  2 单位账户
            if (userType.equals("1")) {
                List<User> users = userMapper.getUserListByOrgId(jsonParam);
                return RespEntity.success(users);
            } else {
                //rest请求单位详情接口，获取单位信息
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("id", homeId);
                com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
                String homeName = businessDetail.getString("name");
                List<User> users = this.userMapper.getUserListB(jsonParam);
                for (User u : users) {
                    u.put("homeName", homeName);
                }
                return RespEntity.success(users);
            }

        } else {
            if (userType.equals("1")) {
                List<User> users = userMapper.getUserListByOrgId(jsonParam);
                return RespEntity.success(users);
            } else {
                //rest请求单位详情接口，获取单位信息
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("id", jsonParam.getStr("homeId"));
                com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
                String homeName = businessDetail.getString("name");
                List<User> users = this.userMapper.getUserListB(jsonParam);
                for (User u : users) {
                    u.put("homeName", homeName);
                }
                return RespEntity.success(users);
            }
        }
    }

    public HashMap<String, String> getOrganizationsTwo(String id) {
        HashMap<String, String> hashMap = new HashMap<>();
        List<Organization> oneList = organizationMapper.selectList(new com.systemsetup.systemsetup.support.mybatisplus.QueryWrapper<Organization>().eq("pid", id));
        for (Organization one : oneList) {
            List<Organization> twoList = getOrganizations(one.getId());
            String id1 = one.getId();
            String name = one.getName();
            hashMap.put(id1, name);
        }
        return hashMap;
    }

    /**
     * 设备导出时调用
     *
     * @param
     * @return
     */
    public RespEntity userInfo(Map<String, Object> map) {
        User user = userMapper.userInfo(map);
        return RespEntity.success(user);
    }

    /**
     * 获取cid
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getCId(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String userId = jsonParam.getStr("userId");
        User user = this.userMapper.selectOne(new QueryWrapper<User>().eq("id", userId));
        if (!user.isEmpty()) {
            return RespEntity.success(user);
        }
        return RespEntity.fail("该用户不存在");
    }

    /**
     * 获取所有和设备号相关的cid
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getAllCidFromNumber(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String allId = jsonParam.getStr("orgIds");
        String[] allIds = allId.split(",");
        if (allIds.length > 0) {
            jsonParam.put("orgIdListFlag", "1");
            jsonParam.put("allIds", allIds);
        }
        List<String> list = userMapper.getAllCidFromNumber(jsonParam);
        return RespEntity.success(list);
    }

    /**
     * 获取所有和设备号相关的openid
     *
     * @param jsonParam
     * @return
     */
    public RespEntity getAllOpenIdFromNumber(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String allId = jsonParam.getStr("orgIds");
        String[] allIds = allId.split(",");
        if (allIds.length > 0) {
            jsonParam.put("orgIdListFlag", "1");
            jsonParam.put("allIds", allIds);
        }
        List<String> list = userMapper.getAllOpenIdFromNumber(jsonParam);
        return RespEntity.success(list);
    }

    /**
     * @Author YangYu
     * @Description 删除openid
     * @Date Created in 13:38 2020/12/14
     * @Param [jsonParam]
     */

    public RespEntity delOpenId(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String openId = jsonParam.getStr("openId");
        if (openId != null && StrUtil.isNotBlank(openId)) {
            weChatMapper.delete(new QueryWrapper<WeChat>().eq("open_id", jsonParam.getStr("openId")));
        }
        //删除openid为空的数据
        weChatMapper.delOpenId();
        return RespEntity.success();
    }

    /**
     * 密码修改
     *
     * @param jsonParam
     * @return
     */
    public RespEntity updatePassWord(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        String oldPwd = jsonParam.getStr("oldPwd");
        String newPwd = jsonParam.getStr("newPwd");
        User user = userMapper.selectById(userId);
        boolean flag = PasswordUtil.validatePassword(oldPwd, user.getAccountpassword());
        if (flag) {
            user.setAccountpassword(PasswordUtil.createHash(newPwd));
            userMapper.updateById(user);
            return RespEntity.success("密码修改成功!");
        }
        return RespEntity.fail("原密码不正确!");
    }

    public RespEntity getOrgNameByOrgName(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Organization organization = this.organizationMapper.selectById(jsonParam.getStr("orgId"));
        if (!organization.isEmpty()) {
            return RespEntity.success(organization);
        }
        return RespEntity.fail();
    }

    /**
     * 角色表增加
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleAdd(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String id = UUID.randomUUID().toString();
        Role role = new Role();
        role.setId(id);
        role.setName(jsonParam.getStr("name"));
        role.setType(userType);
        role.setHomeId(homeId);
        //角色添加
        roleMapper.insert(role);
        //权限设置
        Rolepermission rolepermission = new Rolepermission();
        if (jsonParam.containsKey("permissionsId")) {
            //权限id
            String[] ids = jsonParam.getStr("permissionsId").split(",");
            if (ids != null && ids.length != 0) {
                for (String permissionsId : ids) {
                    if (!permissionsId.equals("0")) {
                        rolepermission.setRoleId(role.getId());
                        rolepermission.setPermissionId(permissionsId);
                        rolepermissionMapper.insert(rolepermission);
                    }
                }
            }
        } else {
            return RespEntity.fail("请选择权限!");
        }

        return RespEntity.success();
    }

    /**
     * 角色详情
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleDetail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String userId = token.getString("user_id");
        Role role = roleMapper.selectById(jsonParam.getStr("id"));
        if (role == null) {
            return RespEntity.fail("角色不存在!");
        }
        String type = "";
        if (homeId.equals("001e7548-8735-4b31-b30b-c9361a62c102")) {
            type = "1";
        } else if (userType.equals("2")) {
            type = "2";
        } else {
            type = "3";
        }
        //查询角色权限id
        List<Rolepermission> rolepermissionList = rolepermissionMapper.selectList(new QueryWrapper<Rolepermission>().eq("role_id", jsonParam.getStr("id")));
        //总权限列表
        List<Permissions> permissionsList = permissionsMapper.getUserPermissionsList(userId);
        Map<String, Object> map = new HashMap<>();
        //第一级权限
        List<Permissions> onePermissionsList = new ArrayList<>();
        //第二级权限
        List<Permissions> twoPermissionsList = new ArrayList<>();
        //第三级权限
        List<Permissions> threePermissionsList = new ArrayList<>();
        //第四级权限
        List<Permissions> fourPermissionsList = new ArrayList<>();
        for (Permissions list : permissionsList) {
            if (list.getLevel() == 1) {
                onePermissionsList.add(list);
            }
            if (list.getLevel() == 2) {
                twoPermissionsList.add(list);
            }
            if (list.getLevel() == 3) {
                threePermissionsList.add(list);
            }
            if (list.getLevel() == 4) {
                fourPermissionsList.add(list);
            }
        }
        for (Permissions one : onePermissionsList) {
            List<Permissions> twoNewPermissionsList = new ArrayList<>();
            for (Permissions two : twoPermissionsList) {
                if (one.getId().equals(two.getPid())) {
                    List<Permissions> threeNewPermissionsList = new ArrayList<>();
                    for (Permissions three : threePermissionsList) {
                        if (two.getId().equals(three.getPid())) {
                            List<Permissions> fourNewPermissionsList = new ArrayList<>();
                            for (Permissions four : fourPermissionsList) {
                                if (three.getId().equals(four.getPid())) {
                                    four = getPermissions(four, rolepermissionList);
                                    fourNewPermissionsList.add(four);
                                }
                            }
                            if (fourNewPermissionsList.size() != 0) {
                                three.put("childList", fourNewPermissionsList);
                            }
                            three = getPermissions(three, rolepermissionList);
                            threeNewPermissionsList.add(three);
                        }
                    }
                    if (threeNewPermissionsList.size() != 0) {
                        two.put("childList", threeNewPermissionsList);
                    }
                    two = getPermissions(two, rolepermissionList);
                    twoNewPermissionsList.add(two);
                }
            }
            if (twoNewPermissionsList.size() != 0) {
                one.put("childList", twoNewPermissionsList);
            }
            one = getPermissions(one, rolepermissionList);
        }
        role.set("permissionsList", onePermissionsList);
        return RespEntity.success(role);
    }

    //权限校验
    public Permissions getPermissions(Permissions permission, List<Rolepermission> rolepermissionList) {
        boolean flag = false;
        for (Rolepermission rolepermission : rolepermissionList) {
            if (permission.getId().equals(rolepermission.getPermissionId())) {
                flag = true;
            }
        }
        permission.put("flag", flag);
        return permission;
    }

    /**
     * 角色表删除
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleDelete(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String id = jsonParam.getStr("id");
        if (id != null && StrUtil.isNotBlank(id)) {
            if (id.equals("001e7548-8735-4b31-b30b-c9361a62c901") || id.equals("001e7548-8735-4b31-b30b-c9361a62c902") || id.equals("001e7548-8735-4b31-b30b-c9361a62c903")) {
                return RespEntity.fail("默认角色不能删除!");
            }
            List<User> userList = userMapper.selectList(new QueryWrapper<User>().eq("role_id", id));
            if (userList.size() > 0) {
                return RespEntity.fail("该角色已绑定账号,无法删除!");
            }
            roleMapper.delete(new QueryWrapper<Role>().eq("id", id));
            rolepermissionMapper.delete(new QueryWrapper<Rolepermission>().eq("role_id", id));
        } else {
            return RespEntity.fail("id为空或为null");
        }
        return RespEntity.success();
    }

    /**
     * 角色编辑
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String id = jsonParam.getStr("id");
        if (id != null && StrUtil.isNotBlank(id)) {
            String name = jsonParam.getStr("name");
            Role role = new Role();
            role.setId(id);
            role.setName(name);
            role.setType(userType);
            role.setHomeId(homeId);
            //角色更新
            roleMapper.updateById(role);
            //角色权限更新
            //权限设置
            Rolepermission rolepermission = new Rolepermission();
            rolepermissionMapper.delete(new QueryWrapper<Rolepermission>().eq("role_id", id));
            if (jsonParam.containsKey("permissionsId")) {
                //权限id
                String[] pid = jsonParam.getStr("permissionsId").split(",");
                if (pid != null && pid.length != 0) {
                    for (String permissionsId : pid) {
                        if (!permissionsId.equals("0")) {
                            rolepermission.setRoleId(role.getId());
                            rolepermission.setPermissionId(permissionsId);
                            rolepermissionMapper.insert(rolepermission);
                        }
                    }
                }
            } else {
                return RespEntity.fail("请选择权限!");
            }
            // 用户权限修改
            List<User> userList = userMapper.selectList(new QueryWrapper<User>().eq("role_id", role.getId()));
            if (userList.size() != 0) {
                for (User user : userList) {
                    userpermissionMapper.delete(new QueryWrapper<Userpermission>().eq("user_id", user.getId()));
                    //权限id
                    String[] pid = jsonParam.getStr("permissionsId").split(",");
                    Userpermission userpermission = new Userpermission();
                    if (pid != null && pid.length != 0) {
                        for (String permissionsId : pid) {
                            if (!permissionsId.equals("0")) {
                                userpermission.setUserId(user.getId());
                                userpermission.setPermissionId(permissionsId);
                                userpermissionMapper.insert(userpermission);
                            }
                        }
                    }
                }

            }
        } else {
            return RespEntity.fail("id不能为空!");
        }

        return RespEntity.success();
    }

    /**
     * 角色分页查询
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        Page<Role> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (!homeId.equals("0")) {
            jsonParam.put("homeId", homeId);
        }
        IPage<Role> pageList = roleMapper.roleListPage(page, jsonParam);
        ;
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * 角色不分页列表
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleListNoPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        List<Role> roleList = null;
        if (homeId.equals("0")) {
            roleList = roleMapper.selectList(new QueryWrapper<Role>());
        } else {
            roleList = roleMapper.selectList(new QueryWrapper<Role>().eq("home_id", homeId));
        }

        return RespEntity.success(roleList);
    }

    /**
     * 角色表不分页列表
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity roleList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        jsonParam.put("type", userType);
        List<Role> roleList = null;
        if (userType.equals("1")) {//机构角色
            roleList = this.roleMapper.selectAll(jsonParam);
        } else if (userType.equals("2")) {//单位角色
            roleList = this.roleMapper.selectAll(jsonParam);
        }
        if (!roleList.isEmpty()) {
            return RespEntity.success(roleList);
        }
        return RespEntity.fail();
    }

    /**
     * 用户设置角色
     *
     * @param jsonParam
     * @return YangYu
     */
    public RespEntity userSetRole(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        if (jsonParam.getStr("userId") != null && StrUtil.isNotBlank(jsonParam.getStr("userId"))) {
            userroleMapper.delUserRole(jsonParam);
            DateTime createtime = DateUtil.date();
            jsonParam.put("createtime", createtime);
            userroleMapper.userSetRole(jsonParam);
        }

        return RespEntity.fail();
    }


    /**
     * 角色和权限关联后的权限列表不分页
     *
     * @param jsonParam
     * @return Li
     */
    public RespEntity rolePermissionsList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String roleId = jsonParam.getStr("roleId");
        //获取角色对应的权限列表
        List<Rolepermission> rolepermissionList = this.rolepermissionMapper.selectList(new QueryWrapper<Rolepermission>().eq("role_id", roleId));
        List<String> perStrs = new ArrayList<>();//存储所有的权限
        for (Rolepermission rolepermission : rolepermissionList) {
            perStrs.add(rolepermission.getPermissionId());
        }
        List<Permissions> permissions = getPermissionsList("0", roleId, perStrs);
        return RespEntity.success(permissions);
    }

    /**
     * 权限列表树
     *
     * @param id
     * @param roleId
     * @param perStrs
     * @return Li
     */
    public List<Permissions> getPermissionsList(String id, String roleId, List<String> perStrs) {
        List<Permissions> list = new ArrayList<>();
        List<Permissions> oneList = permissionsMapper.selectList(new QueryWrapper<Permissions>().eq("pid", id));
        for (Permissions one : oneList) {
            List<Permissions> twoList = getPermissionsList(one.getId(), roleId, perStrs);
            one.put("children", twoList);
            one.put("check", perStrs.contains(one.getId()));
            list.add(one);
        }
        return list;
    }

    /**
     * 角色编辑，设置权限回显
     *
     * @param jsonParam
     * @return Li
     */
    public RespEntity RoleUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String id = jsonParam.getStr("id");
        Role role = this.roleMapper.selectById(id);
        if (!role.isEmpty()) {
            return RespEntity.success(role);
        } else {
            return RespEntity.fail("您查询的id不存在");
        }
    }


    /**
     * 用户设置角色回显
     *
     * @param jsonParam
     * @return Li
     */
    public RespEntity userSetRoleEcho(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        Role userSetRoleEcho = this.roleMapper.userSetRoleEcho(jsonParam);

        if (!userSetRoleEcho.isEmpty()) {
            return RespEntity.success(userSetRoleEcho);
        }

        return RespEntity.fail();
    }


    //获取标题图片
    public RespEntity getHeaderTitle(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
//        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
//        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
//        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String accountName = jsonParam.getStr("accountname");
        if (accountName != null && accountName != "") {
            User user = this.userMapper.selectOne(new QueryWrapper<User>().eq("accountname", accountName));
            //单位或机构id
            String homeId = user.getHomeId();
            //1 机构账户  2 单位账户
            if (user.getType() == 1) {
                Organization organization = this.organizationMapper.selectById(homeId);
                if (organization.getAllId() != null && organization.getAllId() != "") {
                    String bigHomeId = organization.getAllId().split(",")[0];
                    jsonParam.put("homeId", bigHomeId);
                    List<TitlePicture> titlePictureList = this.userroleMapper.getHeaderTitle(jsonParam);
                    for (TitlePicture titlePicture : titlePictureList) {
                        //如果有个性化标题
                        if (titlePicture.getType().equals("2")) {
                            return RespEntity.success(titlePicture);
                        } else {
                            return RespEntity.success(titlePicture);
                        }
                    }
                }
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", homeId);
                com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonObject, "businessJava", "config", "getBusinessDetailNoToken", "business");
                String bigHomeId = businessDetail.getString("orgIds").split(",")[0];
                jsonParam.put("homeId", bigHomeId);
                List<TitlePicture> titlePictureList = this.userroleMapper.getHeaderTitle(jsonParam);
                for (TitlePicture titlePicture : titlePictureList) {
                    //如果有个性化标题
                    if (titlePicture.getType().equals("2")) {
                        return RespEntity.success(titlePicture);
                    } else {
                        return RespEntity.success(titlePicture);
                    }
                }
            }
        }

        return RespEntity.fail();
    }


    /**
     * @Author YangYu
     * @Description 授权
     * @Date Created in 16:57 2023/2/2
     * @Param [jsonParam]
     */

    public RespEntity authorization(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        if (StrUtil.isBlank(jsonParam.getStr("authorizationOrgId"))) {
            return RespEntity.fail("authorizationOrgId不能为空");
        }
        if (StrUtil.isBlank(jsonParam.getStr("authorizedOrgId"))) {
            return RespEntity.fail("authorizedOrgId不能为空");
        }
        //授权机构ID
        String authorizationOrgId = jsonParam.getStr("authorizationOrgId");
        //被授权机构ID
        String authorizedOrgId = jsonParam.getStr("authorizedOrgId");
        //更新机构

        List<Organization> organizationList = organizationMapper.selectList(new QueryWrapper<Organization>().like("all_id", authorizationOrgId));
        if (organizationList.size() > 0) {
            for (Organization organization : organizationList) {
                String[] organizationAllIds = organization.getAllId().split(",");
                //校验是否已授权
                if (!Arrays.asList(organizationAllIds).contains(authorizedOrgId)) {
                    String allId = organization.getAllId() + "," + authorizedOrgId;
                    organizationMapper.updateOrganizationAllId(allId, authorizationOrgId);
                    break;
                }
            }
        }
        //更新单位
        List<Business> businessList = businessMapper.selectList(new QueryWrapper<Business>().like("org_ids", authorizationOrgId));
        if (businessList.size() > 0) {
            for (Business business : businessList) {
                String[] businessAllIds = business.getOrgIds().split(",");
                //校验是否已授权
                if (!Arrays.asList(businessAllIds).contains(authorizedOrgId)) {
                    String allId = business.getOrgIds() + "," + authorizedOrgId;
                    organizationMapper.updateBusinessAllId(allId, authorizationOrgId);
                    break;
                }
            }
        }
        //更新设备
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().like("all_id", authorizationOrgId));
        if (deviceBusinessList.size() > 0) {
            for (DeviceBusiness deviceBusiness : deviceBusinessList) {
                String[] deviceBusinessAllIds = deviceBusiness.getAllId().split(",");
                //校验是否已授权
                if (!Arrays.asList(deviceBusinessAllIds).contains(authorizedOrgId)) {
                    String allId = deviceBusiness.getAllId() + "," + authorizedOrgId;
                    organizationMapper.updateDeviceBusinessAllId(allId, authorizationOrgId);
                    break;
                }
            }
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 取消授权
     * @Date Created in 16:57 2023/2/2
     * @Param [jsonParam]
     */

    public RespEntity cancelAuthorization(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        if (StrUtil.isBlank(jsonParam.getStr("authorizationOrgId"))) {
            return RespEntity.fail("authorizationOrgId不能为空");
        }
        if (StrUtil.isBlank(jsonParam.getStr("authorizedOrgId"))) {
            return RespEntity.fail("authorizedOrgId不能为空");
        }
        //授权机构ID
        String authorizationOrgId = jsonParam.getStr("authorizationOrgId");
        //被授权机构ID
        String authorizedOrgId = jsonParam.getStr("authorizedOrgId");
        //更新机构
        List<Organization> organizationList = organizationMapper.selectList(new QueryWrapper<Organization>().like("all_id", authorizationOrgId));
        if (organizationList.size() > 0) {
            for (Organization organization : organizationList) {
                String[] organizationAllIds = organization.getAllId().split(",");
                //校验是否已授权
                if (Arrays.asList(organizationAllIds).contains(authorizedOrgId)) {
                    String newAllIds = "";
                    for (String allId : organizationAllIds) {
                        if (!allId.equals(authorizedOrgId)) {
                            newAllIds = newAllIds + "," + allId;
                        }
                    }
                    newAllIds = newAllIds.substring(1);
                    organization.setAllId(newAllIds);
                    organizationMapper.updateOrganizationAllId(newAllIds, authorizationOrgId);
                    break;
                }
            }
        }
        //更新单位
        List<Business> businessList = businessMapper.selectList(new QueryWrapper<Business>().eq("org_id", authorizationOrgId));
        if (businessList.size() > 0) {
            for (Business business : businessList) {
                String[] businessAllIds = business.getOrgIds().split(",");
                //校验是否已授权
                if (Arrays.asList(businessAllIds).contains(authorizedOrgId)) {
                    String newAllIds = "";
                    for (String allId : businessAllIds) {
                        if (!allId.equals(authorizedOrgId)) {
                            newAllIds = newAllIds + "," + allId;
                        }
                    }
                    newAllIds = newAllIds.substring(1);
                    organizationMapper.updateBusinessAllId(newAllIds, authorizationOrgId);
                    break;
                }
            }
        }
        //更新设备
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("org_id", authorizationOrgId));
        if (deviceBusinessList.size() > 0) {
            for (DeviceBusiness deviceBusiness : deviceBusinessList) {
                String[] deviceBusinessAllIds = deviceBusiness.getAllId().split(",");
                //校验是否已授权
                if (Arrays.asList(deviceBusinessAllIds).contains(authorizedOrgId)) {
                    String newAllIds = "";
                    for (String allId : deviceBusinessAllIds) {
                        if (!allId.equals(authorizedOrgId)) {
                            newAllIds = newAllIds + "," + allId;
                        }
                    }
                    newAllIds = newAllIds.substring(1);
                    organizationMapper.updateDeviceBusinessAllId(newAllIds, authorizationOrgId);
                    break;
                }
            }
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 设置处置弹框
     * @Date Created in 13:14 2023/2/21
     * @Param [jsonParam]
     */

    public RespEntity setFrameMonitoring(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        FrameMonitoring frameMonitoring = new FrameMonitoring();
        frameMonitoring.setUserId(userId);
        frameMonitoring.setState(jsonParam.getStr("state"));
        frameMonitoring.setTime(jsonParam.getStr("time"));
        frameMonitoringMapper.delete(new QueryWrapper<FrameMonitoring>().eq("user_id", userId));
        frameMonitoringMapper.insert(frameMonitoring);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 设置处置弹框详情 报警未处置，请及时处置！
     * @Date Created in 13:14 2023/2/21
     * @Param [jsonParam]
     */

    public RespEntity setFrameMonitoringDetails(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        FrameMonitoring frameMonitoring = frameMonitoringMapper.selectOne(new QueryWrapper<FrameMonitoring>().eq("user_id", userId));
        if (frameMonitoring == null) {
            frameMonitoring = new FrameMonitoring();
            frameMonitoring.setUserId(userId);
            frameMonitoring.setState("2");
            frameMonitoring.setTime("5");
        }
        return RespEntity.success(frameMonitoring);
    }

    /**
     * @Author YangYu
     * @Description 大屏设置
     * @Date Created in 13:14 2023/2/21
     * @Param [jsonParam]
     */

    public RespEntity largeScreenSettings(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        LargeScreenSettings largeScreenSettings = new LargeScreenSettings();
        largeScreenSettings.setUserId(userId);
        largeScreenSettings.setFile(jsonParam.getStr("fileUrl"));
        largeScreenSettings.setType(jsonParam.getInt("type"));
        largeScreenSettings.setDefaultOption(jsonParam.getInt("defaultOption"));
        largeScreenSettingsMapper.delete(new QueryWrapper<LargeScreenSettings>().eq("user_id", userId).eq("type", jsonParam.getInt("type")));
        largeScreenSettingsMapper.insert(largeScreenSettings);
        aerialViewCoordinateMapper.delete(new QueryWrapper<AerialViewCoordinate>().eq("user_id", userId));
        if (jsonParam.containsKey("coordinateData") && jsonParam.getJSONArray("coordinateData").size() != 0) {
            JSONArray jsonArray = jsonParam.getJSONArray("coordinateData");
            List<AerialViewCoordinate> list = com.alibaba.fastjson.JSONObject.parseArray(jsonArray.toJSONString(0), AerialViewCoordinate.class);
            for (AerialViewCoordinate aerialViewCoordinate : list) {
                aerialViewCoordinate.setUserId(userId);
            }
            aerialViewCoordinateMapper.insertZB(list);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 大屏设置列表
     * @Date Created in 13:14 2023/2/21
     * @Param [jsonParam]
     */

    public RespEntity largeScreenList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        List<LargeScreenSettings> largeScreenSettingsList = largeScreenSettingsMapper.selectList(new QueryWrapper<LargeScreenSettings>().eq("user_id", userId));
        for (LargeScreenSettings largeScreenSettings : largeScreenSettingsList) {
            if (largeScreenSettings.getType() == 1) {
                List<AerialViewCoordinate> aerialViewCoordinateList = aerialViewCoordinateMapper.selectList(new QueryWrapper<AerialViewCoordinate>().eq("user_id", userId));
                largeScreenSettings.put("coordinateData", aerialViewCoordinateList);
                break;
            }
        }
        return RespEntity.success(largeScreenSettingsList);
    }

    /**
     * @Author YangYu
     * @Description 大屏设置删除
     * @Date Created in 13:14 2023/2/21
     * @Param [jsonParam]
     */

    public RespEntity largeScreenDel(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        largeScreenSettingsMapper.delete(new QueryWrapper<LargeScreenSettings>().eq("user_id", userId).eq("type", jsonParam.getInt("type")));
        aerialViewCoordinateMapper.delete(new QueryWrapper<AerialViewCoordinate>().eq("user_id", userId));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 置顶应用新增
     * @Date Created in 14:17 2024/5/11
     * @Param [jsonParam]
     */

    public RespEntity topAppAdd(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        int count = toppedApplicationInfoMapper.selectCount(new QueryWrapper<ToppedApplicationInfo>().eq("user_id",userId).eq("module_id",jsonParam.getStr("moduleId")));
        if (count > 0){
            return RespEntity.fail("应用已置顶无需重置顶!");
        }
        ToppedApplicationInfo toppedApplicationInfo = new ToppedApplicationInfo();
        toppedApplicationInfo.setUserId(userId);
        toppedApplicationInfo.setModuleId(jsonParam.getStr("moduleId"));
        toppedApplicationInfoMapper.insert(toppedApplicationInfo);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 置顶应用删除
     * @Date Created in 14:17 2024/5/11
     * @Param [jsonParam]
     */

    public RespEntity topAppDel(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        toppedApplicationInfoMapper.delete(new QueryWrapper<ToppedApplicationInfo>().eq("user_id",userId).eq("module_id",jsonParam.getStr("moduleId")));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 置顶应用列表
     * @Date Created in 14:17 2024/5/11
     * @Param [jsonParam]
     */

    public RespEntity topAppList(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        List<ToppedApplicationInfo> toppedApplicationInfoList = toppedApplicationInfoMapper.selectList(new QueryWrapper<ToppedApplicationInfo>().eq("user_id",userId));
        return RespEntity.success(toppedApplicationInfoList);
    }

    /**
     * @Author YangYu
     * @Description 更新记录新增、编辑
     * @Date Created in 10:02 2024/5/21
     * @Param [jsonParam]
     */

    public RespEntity renewInfoAddOrUpdate(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");

        String uuid = "";
        if (jsonParam.containsKey("id") && StrUtil.isNotBlank(jsonParam.getStr("id"))){
            uuid = jsonParam.getStr("id");
            renewInfoMapper.deleteById(uuid);
        }else {
            uuid = UUID.randomUUID().toString();
        }
        RenewInfo renewInfo = new RenewInfo();
        renewInfo.setId(uuid);
        renewInfo.setVersion(jsonParam.getStr("version"));
        renewInfo.setContent(jsonParam.getStr("content"));
        renewInfo.setOptimizeContent(jsonParam.getStr("optimizeContent"));
        renewInfo.setRepairContent(jsonParam.getStr("repairContent"));
        renewInfo.setTime(jsonParam.getStr("time"));
        renewInfoMapper.insert(renewInfo);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 更新记录分页列表
     * @Date Created in 10:02 2024/5/21
     * @Param [jsonParam]
     */

    public RespEntity renewInfoListPage(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");

        // 设置页码及查询条数
        Page<RenewInfo> page = new Page(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        // 条件构造器
        QueryWrapper<RenewInfo> queryWrapper = new QueryWrapper();
        // 根据方案名称模糊搜索
        queryWrapper.like(StringUtils.isNotBlank(jsonParam.getStr("content")), "content", jsonParam.get("content")).orderByDesc("time");
        IPage<RenewInfo> renewInfoIPage = renewInfoMapper.selectPage(page, queryWrapper);
        return RespEntity.success(renewInfoIPage);
    }
}
